const User = require('../models/User')
const { generateToken } = require('../utils/jwt')
const Response = require('../utils/response')
const { validationResult } = require('express-validator')

// 用户注册
exports.register = async (req, res) => {
  try {
    // 验证请求参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return Response.error(res, errors.array()[0].msg, 400)
    }

    const { username, password, email, phone } = req.body

    // 检查用户名是否已存在
    const existingUser = await User.findByUsername(username)
    if (existingUser) {
      return Response.error(res, '用户名已存在', 400)
    }

    // 检查邮箱是否已存在
    const existingEmail = await User.findByEmail(email)
    if (existingEmail) {
      return Response.error(res, '邮箱已被注册', 400)
    }

    // 创建用户
    await User.create(username, password, email, phone)

    return Response.success(res, null, '注册成功')
  } catch (error) {
    console.error('注册错误:', error)
    return Response.error(res, '注册失败', 500)
  }
}

// 用户登录
exports.login = async (req, res) => {
  try {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return Response.error(res, errors.array()[0].msg, 400)
    }

    const { username, password } = req.body

    // 查找用户
    const user = await User.findByUsername(username)
    if (!user) {
      return Response.error(res, '用户名或密码错误', 400)
    }

    // 验证密码
    const isValid = await User.validatePassword(password, user.password)
    if (!isValid) {
      return Response.error(res, '用户名或密码错误', 400)
    }

    // 将 is_admin 数字转换为 role 字符串
    const role = user.is_admin === 1 ? 'admin' : 'user'

    // 生成token
    const token = generateToken({
      userId: user.id,
      username: user.username,
      role: role
    })

    return Response.success(res, {
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        role: role
      }
    }, '登录成功')
  } catch (error) {
    console.error('登录错误:', error)
    return Response.error(res, '登录失败', 500)
  }
}

// 获取用户信息
exports.getUserInfo = async (req, res) => {
  try {
    const userId = req.userId
    const user = await User.findById(userId)
    
    if (!user) {
      return Response.notFound(res, '用户不存在')
    }

    return Response.success(res, user)
  } catch (error) {
    console.error('获取用户信息错误:', error)
    return Response.error(res, '获取用户信息失败', 500)
  }
}

// 更新用户信息
exports.updateUserInfo = async (req, res) => {
  try {
    const userId = req.userId
    const { email, phone, avatar } = req.body

    await User.update(userId, { email, phone, avatar })

    return Response.success(res, null, '更新成功')
  } catch (error) {
    console.error('更新用户信息错误:', error)
    return Response.error(res, '更新失败', 500)
  }
}

// 修改密码
exports.changePassword = async (req, res) => {
  try {
    const userId = req.userId
    const { oldPassword, newPassword } = req.body

    // 获取用户信息
    const user = await User.findById(userId)
    if (!user) {
      return Response.notFound(res, '用户不存在')
    }

    // 验证旧密码
    const userWithPassword = await User.findByUsername(user.username)
    const isValid = await User.validatePassword(oldPassword, userWithPassword.password)
    if (!isValid) {
      return Response.error(res, '原密码错误', 400)
    }

    // 修改密码
    await User.changePassword(userId, newPassword)

    return Response.success(res, null, '密码修改成功')
  } catch (error) {
    console.error('修改密码错误:', error)
    return Response.error(res, '密码修改失败', 500)
  }
}

// 删除用户（注销账号）
exports.deleteUser = async (req, res) => {
  try {
    const userId = req.userId

    // 检查用户是否存在
    const user = await User.findById(userId)
    if (!user) {
      return Response.notFound(res, '用户不存在')
    }

    // 删除用户
    await User.delete(userId)

    return Response.success(res, null, '账号已注销')
  } catch (error) {
    console.error('删除用户错误:', error)
    return Response.error(res, '注销账号失败', 500)
  }
}

